<template>
  <div class="hello">
    <div style="position: absolute;top:0;">
        <input style="font-size:16px;" type="file" @change="uploadExcel" />
        <span>选择在线Excel文件：</span>
        <select v-model="selected" @change="selectExcel">
          <option disabled value="">Choose</option>
          <option v-for="option in options" :key="option.text" :value="option.value">
            {{ option.text }}
          </option>
        </select>
        <button @click="downloadExcel">下载保存</button>
        <button @click="loadJsonData">加载JSON数据</button>
    </div>

    <div
      id="luckysheet"
      style="margin:0px;padding:0px;position:absolute;width:100%;left: 0px;top: 30px;bottom:0px;"
    ></div>

    <div v-show="isMaskShow" style="position: absolute;z-index: 1000000;left: 0px;top: 0px;bottom: 0px;right: 0px; background: rgba(255, 255, 255, 0.8); text-align: center;font-size: 40px;align-items:center;justify-content: center;display:flex;">Downloading</div>

  </div>
</template>

<script>
import LuckyExcel from 'luckyexcel'
//导入库export.js 这个文件是es6的，不能在普通的HTML文件直接引入js文件（虽然都是js文件，但是有区别，具体请百度es6与es5）！需要把es6转es5才可以直接引入使用！
import {exportExcel} from './export'

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return {
      selected:"",
      autoFillInfo: [], // {c: 0, d: []}
      indexMap: {}, // { key: index }
      options: [
        { text: 'Money Manager.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/money-manager-2.xlsx' },
        { text: 'Activity costs tracker.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Activity%20costs%20tracker.xlsx' },
        { text: 'House cleaning checklist.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/House%20cleaning%20checklist.xlsx' },
        { text: 'Student assignment planner.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Student%20assignment%20planner.xlsx' },
        { text: 'Credit card tracker.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Credit%20card%20tracker.xlsx' },
        { text: 'Blue timesheet.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Blue%20timesheet.xlsx' },
        { text: 'Student calendar (Mon).xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Student%20calendar%20%28Mon%29.xlsx' },
        { text: 'Blue mileage and expense report.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Blue%20mileage%20and%20expense%20report.xlsx' },
      ],
      isMaskShow: false,
    }

  },
  mounted() {
    console.log(window.luckysheet, 'luckysheet');
    // In some cases, you need to use $nextTick
    // this.$nextTick(() => {
      window.$(function () {
        window.luckysheet.create({
          lang: 'zh',
          container: "luckysheet",
          showinfobar:false,
        });
      });

    // });
  },
  methods:{
    uploadExcel(evt){
        const files = evt.target.files;
        if(files==null || files.length==0){
            alert("No files wait for import");
            return;
        }

        let name = files[0].name;
        let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length-1];
        if(suffix!="xlsx"){
            alert("Currently only supports the import of xlsx files");
            return;
        }
        LuckyExcel.transformExcelToLucky(files[0], function(exportJson, luckysheetfile){

            if(exportJson.sheets==null || exportJson.sheets.length==0){
                alert("Failed to read the content of the excel file, currently does not support xls files!");
                return;
            }
            window.luckysheet.destroy();

            window.luckysheet.create({
                lang: 'zh',
                container: 'luckysheet', //luckysheet is the container id
                showinfobar:false,
                data:exportJson.sheets,
                title:exportJson.info.name,
                userInfo:exportJson.info.name.creator
            });
        });
    },
    selectExcel(evt){
        const value = this.selected;
        const name = evt.target.options[evt.target.selectedIndex].innerText;

        if(value==""){
            return;
        }
        this.isMaskShow = true;

        LuckyExcel.transformExcelToLuckyByUrl(value, name, (exportJson, luckysheetfile) => {

            if(exportJson.sheets==null || exportJson.sheets.length==0){
                alert("Failed to read the content of the excel file, currently does not support xls files!");
                return;
            }

            this.isMaskShow = false;
            window.luckysheet.destroy();

            window.luckysheet.create({
                lang: 'zh',
                container: 'luckysheet', //luckysheet is the container id
                showinfobar:false,
                data:exportJson.sheets,
                title:exportJson.info.name,
                userInfo:exportJson.info.name.creator
            });
        });
    },
    downloadExcel(){
          // const value = this.selected;;
          //
          // if(value.length==0){
          //     alert("Please select a demo file");
          //     return;
          // }
          //
          // var elemIF = document.getElementById("Lucky-download-frame");
          // if(elemIF==null){
          //     elemIF = document.createElement("iframe");
          //     elemIF.style.display = "none";
          //     elemIF.id = "Lucky-download-frame";
          //     document.body.appendChild(elemIF);
          // }
          // elemIF.src = value;
      exportExcel(luckysheet.getAllSheets(),"下载")
      // testaaa();

    },
    handleCellUpdated(r, c, val) {
      console.log(this.autoFillInfo, 'this.autoFillInfo');
      if(this.autoFillInfo.length == 0) { return }
      for(let i = 0; i < this.autoFillInfo.length; i++) {
        let item = this.autoFillInfo[i]
        console.log(item, c, val);
        if(item.c == c) {
          let tmp = item.d.find(e => e.name == val.v)
          if(tmp) {
            console.log(r, this.indexMap, 'this.indexMap');
            window.luckysheet.setCellValue(r, this.indexMap.customAddress, tmp.adress)
            console.log('ok');
          }
          break
        }
      }
    },
    loadJsonData() {
      let that = this
      window.luckysheet.destroy();
      window.luckysheet.create({
        lang: 'zh',
        container: "luckysheet",
        data: [{
          name: "Sheet1",
          "index": 0,
          "status": 1,
          "celldata": []
        }],
        hook: {
          cellUpdated: function (r, c, oldValue, newValue, isRefresh) {
            console.info('cellUpdated',r,c,oldValue, newValue, isRefresh)
            that.handleCellUpdated(r, c, newValue)
          },
        },
        showinfobar:false,
      });
      this.$nextTick(() => {
        setTimeout(() => this.loadJsonDataMain(), 1000)
      })
    },
    loadJsonDataMain() {
      let tableHeader = [
        {
          name: 'orderNumber',
          width: 100,
          fit: true,
          label: '订单编号',
          fixed: true
        },
        {
          name: 'agency',
          width: 100,
          fit: true,
          label: '经销商'
        },
        {
          name: 'customAddress',
          width: 120,
          fit: true,
          label: '终端地址'
        },
        {
          name: 'createTimeLabel',
          width: 150,
          label: '创建日期'
        },
        {
          name: 'totalMoney',
          width: 100,
          label: '总额'
        },
        {
          name: 'shouldMoney',
          width: 100,
          label: '应收金额'
        },
        {
          name: 'discount',
          width: 70,
          label: '折扣'
        },
        {
          name: 'hadMoney',
          width: 100,
          label: '已收金额'
        },
        {
          name: 'payState',
          width: 80,
          label: '付款状态',
          filters: {
            true: '已付清',
            false: '未付清'
          }
        },
        {
          name: 'checkState',
          width: 80,
          label: '审核状态',
          filters: {
            true: '已审核',
            false: '未审核'
          }
        }
      ]
      let tableList = [
        {
          orderNumber: '2310-22',
          agency: '李四',
          customAddress: '成都地址1',
          createTimeLabel: '2023-10-23 17:25:00',
          totalMoney: 9800,
          shouldMoney: 9800,
          discount: 0,
          hadMoney: 3000,
          payState: false,
          checkState: true
        },
        {
          orderNumber: '2310-25',
          agency: '张三',
          customAddress: '成都地址2',
          createTimeLabel: '2023-10-22 13:25:00',
          totalMoney: 19800,
          shouldMoney: 9800,
          discount: 0,
          hadMoney: 10000,
          payState: false,
          checkState: true
        },
      ]
      let agencyList = [
        { name: '经销商1', adress: '地址1' },
        { name: '经销商2', adress: '地址2' },
        { name: '经销商3', adress: '地址3' },
        { name: '经销商4', adress: '地址4' },
        { name: '经销商5', adress: '地址5' },
        { name: '经销商6', adress: '地址6' },
      ]
      this.indexMap = {}
      this.autoFillInfo = []
      // 获取列号
      let r = 0
      for(let i = 0; i < tableHeader.length; i++) {
        let item = tableHeader[i]
        this.indexMap[item.name] = i
        // 为特定字段添加数据验证下拉选项
        if(item.name == 'agency') {
          window.luckysheet.setDataVerification({
            type: 'dropdown',
            type2: null,
            value1: `${agencyList.map(e => e.name).join(',')}`
          }, {
            range: {row:[r+1,r+999], column:[i,i]}
          })
        }
        // 表头
        window.luckysheet.setCellValue(r, i, item.label)
      }
      // 获取自动补齐的数据
      this.autoFillInfo.push({
        c: this.indexMap.agency,
        d: agencyList,
      })
      r += 1
      for(let i = 0; i < tableList.length; i++) {
        let item = tableList[i]
        let itemArr = Object.entries(item)
        for(let j = 0; j < itemArr.length; j++) {
          let v = itemArr[j][1]
          window.luckysheet.setCellValue(r, j, v)
        }
        r++;
      }
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
